package com.etc.service;

import com.etc.entity.User;
import com.etc.entity.chatmessage;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/chatServer", configurator = HttpSessionConfigurator.class)
public class ChatServer {
    private static int onlineCount = 0; //记录在线人数
    private static CopyOnWriteArraySet<ChatServer> webSocketSet = new CopyOnWriteArraySet<ChatServer>();//线程安全的set
    private Session session;    //浏览器中的session回话 
    private User user;      //用户对象
    private HttpSession httpSession;    //request的session
    private static List list = new ArrayList();   //在线列表,记录用户对象
    private static Map routetab = new HashMap();  //放置用户名和socket的sesson
    private static Map<String,Session> rootkefu= new HashMap();//用来存放客服的session
    private static Map routon = new HashMap();  //放置用户咨询状态的sesson
    private static Map rootkefuon= new HashMap();//用来存放客服咨询状态的session
    private static Map roots= new HashMap();
    private String error="发送失败";

   private Logger logger = Logger.getLogger(ChatServer.class);
    @Autowired
    @Qualifier(value = "shior")
    ShiorService shiorService;
    
    //建立回话
    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        this.session = session;
        webSocketSet.add(this);     //加入set中
        onlineCount++;        //在线数加1;
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());//获取Httpsession、
        this.user=(User) httpSession.getAttribute("user");    //获取用户
        chatmessage notice=null;
        if(user.getRoleid().getRolename().equals("kefu")){
            rootkefu.put(user.getUsername(),session);
            notice = new chatmessage(user.getUsername() + "加入咨询室", "notice", list);
           if(!list.contains(user)) {
               list.add(user);//将用户名加入在线列表
           }
        }else{
            routetab.put(user.getUsername(),session);
                 if(rootkefu.isEmpty()){
                     notice = new chatmessage("当前客服不在线，请稍后重试", "notice", list);
                 }else{
                     notice = new chatmessage(user.getUsername() + "加入咨询室", "notice", list);
                 }
            if(!list.contains(user)) {
                list.add(user);//将用户名加入在线列表
            }
        }
        roots.put(user.getUsername(),user);
        String message = new Gson().toJson(notice);
        for(ChatServer chat: webSocketSet){
            try {
                chat.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        onlineCount--;
        list.remove(user.getUsername());
        routetab.remove(user.getUsername());rootkefu.remove(user.getUsername());
        chatmessage notice = new chatmessage(user.getUsername() + "离开咨询室", "notice", list);
        String message = new Gson().toJson(notice);
        //群发通知
        for(ChatServer chat: webSocketSet){
            try {
                chat.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //发送消息
    @OnMessage
        public void onMessage(String message) {
        //客服不在线
        if(rootkefu.isEmpty()){
            chatmessage noonline = new chatmessage("客服不在线，请稍后重试", "noonline", list);
            try{
            this.session.getBasicRemote().sendText(new Gson().toJson(noonline));
        } catch (IOException e) {
                logger.info(error);
            e.printStackTrace();
        }}
        else if(routetab.isEmpty()){
            chatmessage noonline = new chatmessage("没有指定发送对象", "nobody", list);
            try{
                this.session.getBasicRemote().sendText(new Gson().toJson(noonline));
            } catch (IOException e) {
                logger.info(error);
                e.printStackTrace();
            }
        }
        //客服在线
        else {
            //前台信息转为对象
            chatmessage chatmessage = new Gson().fromJson(message, chatmessage.class);
            String type = chatmessage.getType();
            com.etc.entity.chatmessage chatmessage1 = new chatmessage(chatmessage.getMessage(), type, list);
            chatmessage1.setFrom(user.getUsername());
            String from = chatmessage.getFrom();String to=null;
            //获取对象
            User user = (User) roots.get(from);
            chatmessage1.setUser(user);
            //前台消息没有to对象时候，添加一个客服
//            if(chatmessage.getTo()!=null && chatmessage.getTo()!=""){
//                for(Map.Entry<String,Session> entry:rootkefu.entrySet()){
//                   to=entry.getKey();
//                   if(to!=null){
//                chatmessage1.setTo(to);
//                       break;
//                   }
//               }
//            }else{
//                //否则设置消息的to对象为本次to对象
//                chatmessage.setTo(chatmessage.getTo());
//            }

            String s = new Gson().toJson(chatmessage1);
            //群发
            for (ChatServer chat : webSocketSet) {
                try {
                    chat.session.getBasicRemote().sendText(s);
                } catch (IOException e) {
                    logger.info(error);
                    e.printStackTrace();
                }
            }

        }
    }

    @OnError
    public void onError(Throwable error){
        logger.info(error);
        error.printStackTrace();
    }


}
